package org.algorithm.落雪.数组.二月;

/***
 * @author 落雪
 * @date 2022-03-02 星期三 19:22
 *
 *  给定一个数组， 求数组中和为给定target的最短子数组
 *
 * 输入：target = 7, nums = [2,3,1,2,4,3]
 * 输出：2
 * 解释：子数组 [4,3] 是该条件下的长度最小的子数组。
 *
 *  uri: https://leetcode-cn.com/problems/2VG8Kg/
 */
public class 最短子数组 {

    public static void main(String[] args) {
        int[] nums = {2,3,1,2,4,3};
        System.out.println(minSubArrayLen(7, nums));
    }

    public static int minSubArrayLen(int target, int[] nums) {

        int ans = Integer.MAX_VALUE;
        int L = 0, R = L;
        int count = 0;
        while (L<=R && R<nums.length){
            count += nums[R];
            while (count>=target) {
                ans = Math.min(ans,R-L+1);
                count -= nums[L++];
            }
            R++;
        }
        return ans == Integer.MAX_VALUE? 0:ans;

    }
}
